import listener from './listener.js';

/**
 * 格式化日期
 * @param {Date} date
 * @return {string}
 */
function formatTime(date) {
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();
	return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
}

/**
 * 格式化数字
 * @param {*} n
 * @return {string}
 */
function formatNumber(n) {
	n = n.toString();
	return n[1] ? n : '0' + n
}

/**
 * 字符串转日期对象
 * @param {string} str
 * @return {Date}
 */
function stringToDate(str) {
	return new Date(Date.parse(str.replace(/-/g, '/')));
}

/**
 * 字符串转时间戳
 * @param {string} str
 * @return {Number}
 */
function stringToTime(str) {
	return Math.floor(stringToDate(str).getTime() / 1000);
}

/**
 * 执行回调函数
 * @param {function} func
 * @param {*} param
 * @param {*} thisArg
 */
function execFunc(func, param, thisArg) {
	try {
		func && func.call(thisArg, param);
	} catch (e) {
		console.error(e);
	}
}

/**
 * 获取用户信息
 */
function getUserInfo(options) {
	const key = '__USER_INFO__';
	let info = wx.getStorageSync(key);

	if (options.force || !info) {
		listener.once('wx.userinfo.result', (res) => {
			getApp().globalData.isAuthing = false;
			if (res) {
				res = res.userInfo;
				wx.setStorageSync(key, res);
				execFunc(options.success, res, options.thisArg);
			} else {
				res = {errMsg: '授权失败'};
				execFunc(options.fail, res, options.thisArg);
			}
			execFunc(options.complete, res, options.thisArg);
		});
		listener.fire('wx.userinfo.to', options.data);
	} else {
		execFunc(options.success, info, options.thisArg);
		execFunc(options.complete, info, options.thisArg);
	}
}

/**
 * callbacksTransformPromise
 * @param {function} func
 * @param {*} options
 * @return {Promise}
 */
function callbacksTransformPromise(func, options) {
	const callbacks = {
		success: options.success,
		fail: options.fail,
		complete: options.complete
	};
	return promiseSupportCallbacks(new Promise((resolve, reject) => {
		func(Object.assign(options, {
			success: resolve,
			fail: reject,
			complete: undefined
		}));
	}), callbacks);
}

/**
 * promiseSupportCallbacks
 * @param {Promise} promise
 * @param {{success?:function,fail?:function,complete?:function}} callbacks
 * @return {Promise}
 */
function promiseSupportCallbacks(promise, callbacks = {}) {
	if (callbacks.success || callbacks.fail) {
		promise = promise.then(callbacks.success, callbacks.fail);
	}

	if (callbacks.complete) {
		promise = promise.finally(callbacks.complete);
	}
	return promise;
}

export default {
	formatTime,
	stringToDate,
	stringToTime,
	getUserInfo,
	callbacksTransformPromise,
	promiseSupportCallbacks
};